package com.ittony.blog.controller.admin;

import com.ittony.blog.dto.JsonResult;
import com.ittony.blog.entity.Article;
import com.ittony.blog.entity.Comment;
import com.ittony.blog.entity.User;
import com.ittony.blog.enums.UserRole;
import com.ittony.blog.service.ArticleService;
import com.ittony.blog.service.CommentService;
import com.ittony.blog.service.UserService;
import org.checkerframework.checker.units.qual.C;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.*;
import java.util.*;

@Controller
public class AdminController {
    @Autowired
    private UserService userService;

    @Autowired
    private ArticleService articleService;

    @Autowired
    private CommentService commentService;

    @RequestMapping("/admin")
    public String index(Model model, HttpSession session) {
        User user = (User) session.getAttribute("user");
        Integer userId = null;
        if (!UserRole.ADMIN.getValue().equals(user.getUserRole())) {
            userId = user.getUserId();
        }

        List<Article> articleList = articleService.listRecentArticle(userId, 5);
        model.addAttribute("articleList", articleList);

        List<Comment> commentList = commentService.listRecentComment(userId, 5);
        model.addAttribute("commentList", commentList);
        return "Admin/index";
    }

    @RequestMapping("/login")
    public String loginPage(){
        return "Admin/login";
    }

    @RequestMapping("/register")
    public String registerPage(){
        return "Admin/register";
    }

    @RequestMapping(value = "/loginVerify",method = RequestMethod.POST,produces = {"text/plain;charset=UTF-8"})
    @ResponseBody
    public String loginVerify(HttpServletRequest request, HttpServletResponse response){
        Map<String, Object> map = new HashMap<>();

        String username = request.getParameter("username");
        String password = request.getParameter("password");
        String rememberme = request.getParameter("rememberme");
        User user = userService.getUserByNameOrEmail(username);
        if (user == null){
            map.put("code",0);
            map.put("msg","Invalid username");
        } else if (!user.getUserPass().equals(password)){
            map.put("code",0);
            map.put("msg","Invalid password");
        }else if (user.getUserStatus() == 0){
            map.put("code",0);
            map.put("msg","Account disabled");
        } else {
            map.put("code",1);
            map.put("msg","");
            request.getSession().setAttribute("user", user);
            if (rememberme!=null){
                Cookie namecookie = new Cookie("username", username);
                namecookie.setMaxAge(60*60*24*3);
                Cookie pwdCookie = new Cookie("password", password);
                pwdCookie.setMaxAge(60*60*24*3);
                response.addCookie(namecookie);
                response.addCookie(pwdCookie);

            }
            user.setUserLastLoginTime(new Date());
            user.setUserLastLoginIp(getIpAddr(request));
            userService.updateUser(user);
        }
        String result = new JSONObject(map).toString();
        return result;
    }

    @RequestMapping(value = "/registerSubmit",method = RequestMethod.POST)
    @ResponseBody
    public JsonResult registerSubmit(HttpServletRequest request){
        String username = request.getParameter("username");
        String nickname = request.getParameter("nickname");
        String email = request.getParameter("email");
        String password = request.getParameter("password");
        User checkUserName = userService.getUserByName(username);
        if (checkUserName != null){
            return new JsonResult().fail("Username exists");
        }
        User checkEmail = userService.getUserByEmail(email);
        if (checkEmail != null){
            return new JsonResult().fail("Email exists");
        }

        User user = new User();
        user.setUserAvatar("/img/avatar/avatar.png");
        user.setUserName(username);
        user.setUserNickname(nickname);
        user.setUserEmail(email);
        user.setUserPass(password);
        user.setUserStatus(1);
        user.setArticleCount(0);
        user.setUserRole(UserRole.USER.getValue());
        try {
            userService.insertUser(user);
        }catch (Exception e){
            e.printStackTrace();
            return new JsonResult().fail(e.getMessage());
        }
        return new JsonResult().ok("Register success");
    }

    @RequestMapping(value = "/admin/logout")
    public String logout(HttpSession session){
        session.removeAttribute("user");
        session.invalidate();
        return "redirect:/login";
    }

    @RequestMapping(value = "/admin/profile")
    public ModelAndView userProfileView(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        User sessionUser = (User) session.getAttribute("user");
        User user = userService.getUserById(sessionUser.getUserId());
        modelAndView.addObject("user", user);

        modelAndView.setViewName("Admin/User/profile");
        return modelAndView;

    }

    @RequestMapping(value = "/admin/profile/edit")
    public ModelAndView editUserView(HttpSession session){
        ModelAndView modelAndView = new ModelAndView();
        User loginUser = (User) session.getAttribute("user");
        User user = userService.getUserById(loginUser.getUserId());
        modelAndView.addObject("user", user);

        modelAndView.setViewName("Admin/User/editProfile");
        return modelAndView;
    }

    @RequestMapping(value = "/admin/profile/save",method = RequestMethod.POST)
    public String saveProfile(User user,HttpSession session){
        User dbUser =(User) session.getAttribute("user");

        user.setUserId(dbUser.getUserId());
        userService.updateUser(user);
        return "redirect:/admin/profile";
    }
}
